<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Container;
use think\facade\App;
use think\facade\Config;

class Prod extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('prod')
            ->addArgument('mode', Argument::REQUIRED, 'mode is 1 or 0')
            ->setDescription('Enable or disable the production environment');
    }

    protected function execute(Input $input, Output $output)
    {
        $mode   = $input->getArgument('mode') ?: 0;
        $runtimePath = App::getRuntimePath();
        if($mode==1){
            $content     = '<?php ' . PHP_EOL . $this->buildConfig($output);
            file_put_contents($runtimePath . 'allconfig.php', $content);
            $output->writeln("<info>Successfully enable production mode</info>");
        }else{
            @unlink($runtimePath . 'allconfig.php');
            $output->writeln("<info>Successfully enable developer mode</info>");
        }
    }



    protected function buildConfig($output)
    {
        $content    = '//iDapp generated at:' . date('Y-m-d H:i:s') . PHP_EOL;
        $configPath = App::getConfigPath();
        $ext        = App::getConfigExt();
        //$config     = Container::get('config');
        $files = is_dir($configPath) ? scandir($configPath) : [];
        foreach ($files as $file) {
            if ('.' . pathinfo($file, PATHINFO_EXTENSION) === $ext) {
                $filename = $configPath . $file;
                Config::load($filename, pathinfo($file, PATHINFO_FILENAME));
            }
        }
        // 加载行为扩展文件
        /*if (is_file($path . 'tags.php')) {
            $tags = include $path . 'tags.php';
            if (is_array($tags)) {
                $content .= PHP_EOL . '\think\facade\Hook::import(' . (var_export($tags, true)) . ');' . PHP_EOL;
            }
        }
        if (is_file($path . 'provider.php')) {
            $provider = include $path . 'provider.php';
            if (is_array($provider)) {
                $content .= PHP_EOL . '\think\Container::getInstance()->bindTo(' . var_export($provider, true) . ');' . PHP_EOL;
            }
        }*/
        $content .= PHP_EOL . 'return ' . var_export(Config::get(), true) . ';' . PHP_EOL;

        return $content;
    }
}
